<?php
namespace Core\Plugin;
use \Core\Exception;

/**
 * Common API Rules.
 */
class Rules
{
    protected $variable = [];
    protected $rule = '';
    public $result = '';

    public function __construct()
    {

    }

    public function set($field, $value)
    {
        $this->variable[] = $field;
        $this->$field = $value;
        return $this;
    }

    public function rule($rule){
        $this->rule = $rule;
        return $this;
    }

    public function validate()
    {
        if (empty($this->rule))
        {
            return false;
        }
        $this->result = preg_replace_callback_array([
            '/#(.*?)#/is'=>[$this, 'parseVar'],
            '/\{(.*?)\}/is'=>[$this, 'parseVar']
        ], $this->rule);
        return eval("if ({$this->result}){return true;}else{return false;}");
    }

    public function toJson($array = [])
    {
        if (empty($array))
        {
            $array = $this->rules;
        }
        return json_encode($array);
    }

    private function parseVar($var)
    {
        if (preg_match('/([a-zA-Z_][a-zA-Z0-9_]*)\.([a-zA-Z_][a-zA-Z0-9_]*)/is', $var[1], $vars)){
            $variable = $vars[1];
            return isset($this->$variable[$vars[2]]) ? $this->$variable[$vars[2]] : $var[1];
        }else{
            foreach($this->variable AS $variable)
            {
                if (!isset($this->$variable[$var[1]])){
                    continue;
                }
                $value = $this->$variable[$var[1]];
                if (gettype($value) == 'string'){
                    return "'{$value}'";
                }
                return $value;
            }
            return $var[1];
        }
    }

}